package com.huan.springcloud.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 替换BeanFactory的实现类
 *
 * @author huan.fu
 * @date 2022/7/16 - 09:45
 */
@Slf4j
@Component
public class BeanLoadTimeCostApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        if (applicationContext instanceof GenericApplicationContext) {
            log.info("BeanLoadCostApplicationContextInitializer run");
            BeanLoadTimeCostBeanFactory beanFactory = new BeanLoadTimeCostBeanFactory();
            Field field;
            try {
                field = GenericApplicationContext.class.getDeclaredField("beanFactory");
                field.setAccessible(true);
                field.set(applicationContext, beanFactory);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
